//导入重置样式
require("../../assets/css/reset.css");
//导入公共样式
require("../../assets/css/basic.css");
//导入标准样式
require("../../assets/css/normalize.css");
//导入iconfont.css
require("../../assets/fonts/iconfont.css");
//导入样式
require("./sports_course_play.less");
//引入js模块
const dom = require("../../utils/dom.js");
//引入axios公共工具
const axios = require("../../utils/axios.js");

document.addEventListener("DOMContentLoaded", function () {
	
	//1.渲染数据到页面上
	const fragments = JSON.parse(localStorage.getItem("fragments"));

	let n = 0; //用一个变量控制当前播放的节
	let video = dom.get("#video");
	let proc = dom.get(".progress-bar");
	let timer = null;
	let startTime = Date.now(); //进入页面开始计时
	let duration = 0; //持续时间
	//2. 定义一个函数，用于播放视频
	function play() {
		dom.get("#curPart").textContent = n + 1;
		dom.get("#totalPart").textContent = fragments.length;
		dom.get("#title").textContent = fragments[n].title;
		video.src = axios.defaults.baseURL + fragments[n].videoUrl;
		video.play();

		//进度条
		timer = setInterval(function () {
			proc.style.width = (100 * video.currentTime) / video.duration + "%";
		}, 50);
	}
	play();

	//3. 播放一节结束，自动接下一节
	video.addEventListener("ended", function () {
		n++;
		if (n < fragments.length) {
			play();
		} else {
			n = fragments.length - 1;
		}
	});

	//4. 上一节
	dom.get(".zp-previous").addEventListener("click", function () {
		n--;
		if (n < 0) {
			n = 0;
		}
		play();
	});

	//5. 下一节
	dom.get(".zp-next").addEventListener("click", function () {
		n++;
		if (n >= fragments.length) {
			n = fragments.length - 1; //设置成最后一节
		}
		play();
	});
	//6.隐藏弹出层
	dom.get("#mask").addEventListener("click", function () {
		this.style.display = "none";
		dom.get("#box").style.display = "none";
		video.play();
	});
	//7.点击暂停显示弹出层
	dom.get(".zp-stop").addEventListener("click", function () {
		dom.get("#mask").style.display = "block";
		video.pause(); //视频暂停
		dom.get("#box").style.display = "flex";
		//计算时间
		duration += Date.now() - startTime;
		console.log(duration);
	});
	//8.继续训练
	dom.get("#playBox").addEventListener("click", function () {
		dom.get("#mask").style.display = "none";
		dom.get("#box").style.display = "none";
		video.play();
		//重新计时
		startTime = Date.now();
	});
	//9.结束训练
	dom.get("#endBox").addEventListener("click", function () {
		duration = Math.floor(duration / 1000);
		let calorie = Math.ceil(duration * 1.57);
		axios
			.post("/api/exercise/save", {
				type: 2,
				duration,
				calorie,
			})
			.then((res) => {
				if (res.data.errno === 0) {
					alert("训练结束");
					location.href = "sports-course.html";
				}
			});
	});
});
